package com.newgrand.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.newgrand.mapper.*;
import com.newgrand.model.*;
import com.newgrand.utils.i8util.HttpHelper;
import com.newgrand.utils.i8util.PropHelper;
import com.newgrand.utils.i8util.StringHelper;
import com.newgrand.utils.uuid.GetNewPhidUtils;
import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: zhanglixin
 * @Data: 2022/10/31 10:59
 * @Description: TODO
 */
@Service
public class WorkFlowService {


    @Value("${i8.databaseName}")
    private String i8DbName;

    @Value("${oa.registerCode}")
    private String registerCode;


    @Value("${i8.url}")
    private String i8Url;

    @Value("${i8.appurl}")
    private String i8App;
    @Value("${oa.url}")
    private String oaUrl;
    @Value("${oa.username}")
    private String oaUsername;
    @Value("${oa.password}")
    private String oaPassword;

    @Autowired
    private PropHelper env;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UipLog dbLog;

    @Autowired
    private HttpHelper httpHelper;


    @Autowired
    private SecDevTaskMsgMapper secDevTaskMsgMapper;

    @Autowired
    private SecDevMessageMapper secDevMessageMapper;

    @Autowired
    private SecDevProcnotifMsgMapper secDevProcnotifMsgMapper;

    @Autowired
    private Fg3UserMapper fg3UserMapper;
    @Autowired
    private ActHiTaskinstMapper actHiTaskinstMapper;


    public I8ReturnModel Send(String jsonStr) throws Exception {
        I8ReturnModel rv = new I8ReturnModel();
        try{
            dbLog.info("taskmsg", "产品推送", jsonStr);
            //先将接收到的数据插入中间表 AddNew 状态的数据
            JSONArray workflowJA = JSON.parseArray(jsonStr);
            int wfCount = workflowJA.size();
            for(int i=0;i<wfCount;i++){
                JSONObject wf = workflowJA.getJSONObject(i);
                String taskid = wf.getString("taskid");
                String title = wf.getString("title");
                String url = wf.getString("url");
                String dbName = wf.getString("dbName");
                if(!i8DbName.equals(dbName)) continue; //非当前启用账套
                String currentUser = wf.getString("currentUser");
                String status = wf.getString("status");
                if(!"addNew".equals(status)) continue; //只记录AddNew数据
                JSONArray usersJA = wf.getJSONArray("users");
                int userCount = usersJA.size();
                for(int m=0;m<userCount;m++){
                    String userid = usersJA.getString(m);
                    String phid = GetNewPhidUtils.getPhid();
                    secDevTaskMsgMapper.delete(
                            new QueryWrapper<SecDevTaskMsg>()
                                    .lambda().
                                    eq(SecDevTaskMsg::getTaskid,taskid)
                                    .eq(SecDevTaskMsg::getUserid,userid)
                                    .eq(SecDevTaskMsg::getPushadd,'0')
                                    .eq(SecDevTaskMsg::getPushdone,'0')
                                    .eq(SecDevTaskMsg::getPushdel,'0'));
                    //记录数据库
                    SecDevTaskMsg secDevTaskMsg = SecDevTaskMsg.builder()
                            .phid(phid).taskid(taskid).userid(userid).url(url).dbname(dbName).status("addNew")
                            .build();
                    secDevTaskMsgMapper.insert(secDevTaskMsg);
                }
            }

            for(int i=0;i<wfCount;i++){
                JSONObject wf = workflowJA.getJSONObject(i);
                String taskid = wf.getString("taskid");
                String title = wf.getString("title");
                String url = wf.getString("url");
                String dbName = wf.getString("dbName");
                if(!i8DbName.equals(dbName)) continue; //非当前启用账套
                String currentUser = wf.getString("currentUser");
                String status = wf.getString("status");
                JSONArray usersJA = wf.getJSONArray("users");
                int userCount = usersJA.size();
                SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if("addNew".equals(status))
                {
                    //新增待办
                    List<Map<String, Object>> wfInfo = jdbcTemplate.queryForList(
                            "SELECT p.id_ insid,t.NAME_ as nodename,t.START_TIME_ receivedatetime,p.START_TIME_ createdatetime,\n" +
                                    "u1.phid as creatorphid,u1.userno startuserno,pd.NAME_ pdname,p.BUSINESS_KEY_ keyname,anbi.bizname as workflowname\n" +
                                    "FROM ACT_HI_TASKINST t\n" +
                                    "JOIN ACT_HI_PROCINST p ON t.PROC_INST_ID_ =p.ID_\n" +
                                    "JOIN fg3_user u1 ON u1.phid =p.START_USER_ID_ \n" +
                                    "JOIN ACT_RE_PROCDEF pd ON pd.ID_ =p.PROC_DEF_ID_\n" +
                                    "Join ACT_NG_BIZCOMPONENT anbcp on anbcp.componentid=t.form_resource_key_\n" +
                                    "Join act_ng_bizinfo anbi on anbi.Bizid=anbcp.bizid\n" +
                                    "WHERE t.ID_=?",taskid);
                    if (wfInfo != null && wfInfo.size() > 0) {
                        Map<String, Object> workFlow = wfInfo.get(0);
                        String insid = StringHelper.nullToEmpty(workFlow.get("insid"));//流程id
                        String workflowname = StringHelper.nullToEmpty(workFlow.get("workflowname"));//流程类型名称
                        String nodename = StringHelper.nullToEmpty(workFlow.get("nodename"));//步骤名称(节点名称)
                        String creatorphid = StringHelper.nullToEmpty(workFlow.get("creatorphid"));//创建人phid
                        String createdatetime = bartDateFormat.format(wfInfo.get(0).get("createdatetime"));
                        String receivedatetime = bartDateFormat.format(wfInfo.get(0).get("receivedatetime"));
                        for(int m=0;m<userCount;m++){
                            String userid = usersJA.getString(m);//接收人phid
                            JSONObject root_push = new JSONObject();
                            Fg3User receiverInfo = fg3UserMapper.selectById(userid);
                            Fg3User creatorInfo = fg3UserMapper.selectById(creatorphid);
                            String receiver = receiverInfo.getUserno();
                            String creator = creatorInfo.getUserno();

                            root_push.put("registerCode",registerCode);//注册系统编码
                            root_push.put("taskId",taskid+"_"+userid);//第三方系统待办主键
                            root_push.put("title",title);//待办标题
                            //20230612增加紧急程度判断
                            if(title.endsWith("紧急")&&title.contains("中标信息风险测试")){
                                root_push.put("classify","3");
                            }else if(title.endsWith("高")&&title.contains("中标信息风险测试")){
                                root_push.put("classify","2");
                            }else{
                                root_push.put("classify","1");
                            }

                            root_push.put("senderName",creatorInfo.getUsername());//待办发起人姓名
                            //root_push.put("classify",nodename);//类别   字段作废
                            root_push.put("contentType",workflowname);//内容类型
                            root_push.put("state","0");//状态0待办，1已办
                            root_push.put("thirdSenderId",creator);//第三方系统发送者主键
                            root_push.put("thirdReceiverId",receiver);//第三方系统接收人主键
                            root_push.put("creationDate",createdatetime);//待办发起日期，格式yyyy-MM-dd HH:mm:ss
                            root_push.put("content","");//原生app的下载地址

                            root_push.put("noneBindingSender",creator);//登录名称/人员编码/手机号/电子邮件
                            root_push.put("noneBindingReceiver",receiver);//登录名称/人员编码/手机号/电子邮件

                            //组装PCurl链接地址
                            String pwd = StringHelper.nullToEmpty(receiverInfo.getPwd());
                            String org = receiverInfo.getLastloginorg();
                            if (url.startsWith("/")) {
                                url = url.substring(1);
                            }//统一去掉第一个斜杠
                            String base64openUrl = URLEncoder.encode(url, "UTF-8");
                            //Sup/NG3WebLogin/SignLogin
                            String pcurl = i8Url + "/Hnlj/TaskMsg/wfmsg?logid=" + receiver+ "&database=" + i8DbName + "&orgid=" + org + "&openUrl=" + base64openUrl + "&urlTitle=&openAlone=true";

                            root_push.put("url",pcurl);//PC穿透地址
                            //组装app链接地址
                            JSONObject pushdata = new JSONObject();
                            JSONObject pushdatadata = new JSONObject();
                            pushdatadata.put("piid", insid);
                            pushdatadata.put("taskinstid", taskid);
                            pushdata.put("data", pushdatadata);
                            String pushdd = URLEncoder.encode(pushdata.toJSONString(), "UTF-8");
                            String appurl = i8App + "&requestType=MEA&defaultTab=1&userid=" + receiver + "_" + i8DbName.replace("NG","") + "&pushdata=" + pushdd;
                            root_push.put("h5url",appurl);//H5穿透地址

                            StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                            entity.setContentType("application/json");
                            Header[] headers = new Header[1];
                            Header header = new BasicHeader("Content-Type","application/json");
                            headers[0] = header;
                            //获取token
                            String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                            JSONObject tokenPush = new JSONObject();
                            tokenPush.put("userName", oaUsername);
                            tokenPush.put("password", oaPassword);
                            StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                            tokenEntity.setContentType("application/json");
                            ///"+oaUsername+"/"+oaPassword
                            String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                            String token = "";
                            if(!StringUtils.isEmpty(tokenMsg)){
                                dbLog.info("addNew", "推送新增待办获取token", "接口返回:"+tokenMsg);
                                JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                                token = tokenJO.getString("id");
                            }
                            String addNewUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/receive?token="+token;
                            String rtnMsg = httpHelper.Post(addNewUrl,entity,headers);
                            dbLog.info("addNew", "推送新增待办", addNewUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                            int j=0;//{"return":{"returnState":2,"message":"消息入队成功 | 4bd2a885-6af5-4c7c-91f7-89645046c17b"}}
                            //更新新增待办推送标识和时间
                            if(!StringUtils.isEmpty(rtnMsg)){
                                JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                                if("true".equals(joRtn.getString("success"))){
                                    Date nowTime = new Date();
                                    UpdateWrapper updateWrapper = new UpdateWrapper();
                                    updateWrapper.eq("taskid", taskid);
                                    updateWrapper.eq("userid", userid);
                                    updateWrapper.set("pushadd","1");
                                    updateWrapper.set("pushaddtime",bartDateFormat.format(nowTime));
                                    secDevTaskMsgMapper.update(null,updateWrapper);

                                    //再发个消息通知
                                    JSONObject msgPushJO = new JSONObject();
                                    msgPushJO.put("thirdpartyRegisterCode",registerCode);//注册系统编码
                                    msgPushJO.put("thirdpartyMessageId",taskid+"_"+userid);//第三方系统待办主键
                                    msgPushJO.put("messageContent",title);//待办标题
                                    msgPushJO.put("downloadUrl","");//原生app的下载地址
                                    msgPushJO.put("thirdpartySenderId",creator);//第三方系统发送者主键
                                    msgPushJO.put("thirdpartyReceiverId",receiver);//第三方系统接收人主键
                                    msgPushJO.put("creation_date",createdatetime);//待办发起日期，格式yyyy-MM-dd HH:mm:ss
                                    msgPushJO.put("noneBindingSender",creator);//登录名称/人员编码/手机号/电子邮件
                                    msgPushJO.put("noneBindingReceiver",receiver);//登录名称/人员编码/手机号/电子邮件
                                    msgPushJO.put("messageURL",pcurl);//PC穿透地址
                                    msgPushJO.put("messageH5URL",appurl);//H5穿透地址
                                    StringEntity msgEntity = new StringEntity(msgPushJO.toJSONString(), Charset.forName("UTF-8"));
                                    msgEntity.setContentType("application/json");
                                    String addMsgUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyMessage/receive/singleMessage?token="+token;
                                    String pushMsgRtn = httpHelper.Post(addMsgUrl,msgEntity,headers);
                                    dbLog.info("addMsg", "推送新增消息通知", addMsgUrl+"推送:"+msgPushJO.toJSONString()+"接口返回:"+pushMsgRtn);

                                }
                            }


                        }
                    }
                }else if("done".equals(status))
                {
                    //已办
                    String instID = url.substring(url.indexOf("wfpiid=")+7,url.indexOf("&wftaskid="));
                    List<Map<String, Object>> billInfoMap = jdbcTemplate.queryForList("SELECT anb.BIZNAME as modelName FROM ACT_HI_PROCINST ahp\n" +
                            "LEFT JOIN act_ng_processtrace anp ON ahp.ID_=anp.INSTCODE\n" +
                            "LEFT JOIN act_ng_bizinfo anb ON anb.BIZID=anp.BIZID\n" +
                            "WHERE ahp.ID_=?",instID);
                    String modelName = "";
                    if (billInfoMap != null && billInfoMap.size() > 0) {
                        Map<String, Object> bill = billInfoMap.get(0);
                        //查询模块名称
                        modelName = StringHelper.nullToEmpty(bill.get("modelName"));
                    }
                    for(int m=0;m<userCount;m++){
                        String userid = usersJA.getString(m);//接收人phid
                        JSONObject root_push = new JSONObject();
                        root_push.put("registerCode",registerCode);//注册系统编码
                        root_push.put("taskId",taskid+"_"+userid);//第三方系统待办主键
                        root_push.put("state","1");//状态：0:未办理；1:已办理
                        root_push.put("subState","0");//处理后状态：0/1/2/3同意已办/不同意已办/取消/驳回

                        Fg3User receiverInfo = fg3UserMapper.selectById(userid);
                        String receiver = receiverInfo.getUserno();

                        StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                        entity.setContentType("application/json");
                        Header[] headers = new Header[1];
                        Header header = new BasicHeader("Content-Type","application/json");
                        headers[0] = header;
                        //获取token
                        String token = "";
                        String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                        JSONObject tokenPush = new JSONObject();
                        tokenPush.put("userName", oaUsername);
                        tokenPush.put("password", oaPassword);
                        StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                        tokenEntity.setContentType("application/json");
                        ///"+oaUsername+"/"+oaPassword
                        String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                        if(!StringUtils.isEmpty(tokenMsg)){
                            dbLog.info("done", "推送已办获取token", "接口返回:"+tokenMsg);
                            JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                            token = tokenJO.getString("id");
                        }
                        String doneUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/updatePendingState?token="+token;
                        String rtnMsg = httpHelper.Post(doneUrl,entity,headers);
                        int j=0;
                        dbLog.info("done", "推送已办", doneUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                        //更新新增待办推送标识和时间
                        if(!StringUtils.isEmpty(rtnMsg)){
                            JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                            if("true".equals(joRtn.getString("success"))){
                                Date nowTime = new Date();
                                UpdateWrapper updateWrapper = new UpdateWrapper();
                                updateWrapper.eq("taskid", taskid);
                                updateWrapper.eq("userid", userid);
                                updateWrapper.set("pushdone","1");
                                updateWrapper.set("pushdonetime",bartDateFormat.format(nowTime));
                                secDevTaskMsgMapper.update(null,updateWrapper);
                            }
                        }



                    }
                }else if("delete".equals(status))
                {
                    //删除待办

                    for(int m=0;m<userCount;m++){
                        String userid = usersJA.getString(m);//接收人phid
                        JSONObject root_push = new JSONObject();
                        root_push.put("registerCode",registerCode);//注册系统编码
                        root_push.put("taskId",taskid+"_"+userid);//第三方系统待办主键
                        root_push.put("state","1");//状态：0:未办理；1:已办理
                        root_push.put("subState","2");//处理后状态：0/1/2/3同意已办/不同意已办/取消/驳回

                        Fg3User receiverInfo = fg3UserMapper.selectById(userid);
                        String receiver = receiverInfo.getUserno();

                        StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                        entity.setContentType("application/json");
                        Header[] headers = new Header[1];
                        Header header = new BasicHeader("Content-Type","application/json");
                        headers[0] = header;
                        //获取token
                        String token = "";
                        String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                        JSONObject tokenPush = new JSONObject();
                        tokenPush.put("userName", oaUsername);
                        tokenPush.put("password", oaPassword);
                        StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                        tokenEntity.setContentType("application/json");
                        ///"+oaUsername+"/"+oaPassword
                        String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                        if(!StringUtils.isEmpty(tokenMsg)){
                            dbLog.info("delete", "推送删除待办获取token", "接口返回:"+tokenMsg);
                            JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                            token = tokenJO.getString("id");
                        }
                        String delUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/updatePendingState?token="+token;
                        String rtnMsg = httpHelper.Post(delUrl,entity,headers);

                        int j=0;
                        dbLog.info("delete", "推送删除待办", delUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                        //更新新增待办推送标识和时间
                        if(!StringUtils.isEmpty(rtnMsg)){
                            JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                            if("true".equals(joRtn.getString("success"))){
                                Date nowTime = new Date();
                                UpdateWrapper updateWrapper = new UpdateWrapper();
                                updateWrapper.eq("taskid", taskid);
                                updateWrapper.eq("userid", userid);
                                updateWrapper.set("pushdel","1");
                                updateWrapper.set("pushdeltime",bartDateFormat.format(nowTime));
                                secDevTaskMsgMapper.update(null,updateWrapper);
                            }
                        }


                    }
                }

            }

        }catch (Exception ex){
            rv.setMessage("接口出现异常:"+ex.getMessage());
        }
        return rv;
    }

    public Map<String, String> GetPars(String url) {
        Map<String, String> map = null;
        if (url != null && url.indexOf("&") > -1 && url.indexOf("=") > -1) {
            url = url.substring(url.indexOf("?") + 1);
            map = new HashMap<String, String>();
            String[] arrTemp = url.split("&");
            for (String str : arrTemp) {
                String[] qs = str.split("=");
                map.put(qs[0], qs[1]);
            }
        }
        return map;
    }



    /**
     * 定时推送新增待办接口
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void pushAddNew(){
        try{
            List<Map<String, Object>> wfInfo = jdbcTemplate.queryForList(
                    "SELECT i8task.taskid,i8task.userid,i8task.title,i8task.compurl,\n" +
                            "                                            i8task.bizurl,i8task.COMPONENTID,i8task.instcode,i8task.billid FROM (\n" +
                            "                            select art.ID_ taskid, COALESCE(art.ASSIGNEE_, ari.USER_ID_) userid,ahp.ID_ as instcode,\n" +
                            "                            ahp.BUSINESS_KEY_ AS title,anb.URL AS compurl,biz.URL AS bizurl,anp.pk1 as billid,anb.COMPONENTID\n" +
                            "                            from ACT_RU_TASK art\n" +
                            "                            left join ACT_RU_IDENTITYLINK ari on art.ID_ = ari.TASK_ID_\n" +
                            "                            LEFT JOIN act_hi_taskinst aha ON art.id_=aha.ID_\n" +
                            "                            LEFT JOIN ACT_NG_BIZCOMPONENT anb ON aha.FORM_RESOURCE_KEY_=anb.COMPONENTID\n" +
                            "                            LEFT JOIN act_ng_bizinfo biz ON biz.BIZID=anb.BIZID\n" +
                            "                            LEFT JOIN ACT_HI_PROCINST ahp ON ahp.ID_=aha.PROC_INST_ID_\n" +
                            "                            left join act_ng_processtrace anp on anp.instcode=ahp.ID_\n" +
                            "                            ) i8task\n" +
                            "                            WHERE i8task.billid is not null and i8task.userid is not null and NOT exists(\n" +
                            "                            SELECT phid FROM (SELECT phid,taskid,userid FROM sec_dev_task_msg WHERE pushadd='1') sdtm WHERE sdtm.taskid=i8task.taskid AND sdtm.userid=i8task.userid\n" +
                            "                            )");
            if (wfInfo != null && wfInfo.size() > 0) {
                int count = wfInfo.size();
                dbLog.info("pushAddNew", "推送新增待办异常", "满足条件条数:"+count);
                for(int i=0;i<count;i++){
                    Map<String, Object> workFlow = wfInfo.get(i);

                    JSONObject jo = new JSONObject();
                    JSONArray pushJA = new JSONArray();
                    String taskid = StringHelper.nullToEmpty(workFlow.get("taskid"));
                    String userid = StringHelper.nullToEmpty(workFlow.get("userid"));
                    if (StringUtils.isEmpty(userid)) continue;
                    String compurl = StringHelper.nullToEmpty(workFlow.get("compurl"));
                    String bizurl = StringHelper.nullToEmpty(workFlow.get("bizurl"));
                    String instcode = StringHelper.nullToEmpty(workFlow.get("instcode"));
                    String billid = StringHelper.nullToEmpty(workFlow.get("billid"));
                    if (StringUtils.isEmpty(billid)) continue;
                    String funUrl = "";
                    String url = StringUtils.isEmpty(compurl) ? bizurl : compurl;
                    url = url.startsWith("/")?url.substring(1) : url;
                    String templateUrl = "wfpiid="+instcode+"&wftaskid="+taskid+"&wfotype=taskhandle&id="+billid+"&otype=edit";
                    if (url.contains("?"))
                    {
                        funUrl = url + "&";
                    }
                    else
                    {
                        funUrl = url + "?";
                    }
                    funUrl = funUrl + templateUrl;
                    jo.put("taskid", taskid);
                    jo.put("title", StringHelper.nullToEmpty(workFlow.get("title")));
                    jo.put("url", funUrl);
                    jo.put("dbName", i8DbName);
                    jo.put("currentUser", userid);
                    JSONArray users = new JSONArray();
                    users.add(userid);
                    jo.put("users", users);
                    jo.put("status", "addNew");
                    pushJA.add(jo);

                    Send(pushJA.toString());
                }
            }
        }catch (Exception ex){
            dbLog.info("pushAddNew", "推送新增待办异常", ex.getMessage());
        }
    }


    /**
     * 定时推送已办或删除待办接口
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void pushDoneDel(){
        try{
            List<Map<String, Object>> wfInfo = jdbcTemplate.queryForList(
                    "SELECT sdtm.taskid,sdtm.userid,sdtm.url,ahp.ID_ as instcode,aht.ID_ AS i8taskid,\n" +
                            "                            aht.ASSIGNEE_ AS i8userid,\n" +
                            "                            aht.DELETE_REASON_ AS i8status,\n" +
                            "                            ahp.BUSINESS_KEY_ AS title,anb.URL AS compurl,biz.URL AS bizurl,anp.pk1 as billid \n" +
                            "                            FROM sec_dev_task_msg sdtm\n" +
                            "                            LEFT JOIN act_hi_taskinst aht ON aht.ID_=sdtm.taskid\n" +
                            "                            LEFT JOIN ACT_NG_BIZCOMPONENT anb ON aht.FORM_RESOURCE_KEY_=anb.COMPONENTID\n" +
                            "                            LEFT JOIN act_ng_bizinfo biz ON biz.BIZID=anb.BIZID\n" +
                            "                            LEFT JOIN ACT_HI_PROCINST ahp ON ahp.ID_=aht.PROC_INST_ID_\n" +
                            "                            left join act_ng_processtrace anp on anp.instcode=ahp.ID_\n" +
                            "                            WHERE (sdtm.pushadd='1' AND sdtm.pushdone<>'1' AND sdtm.pushdel<>'1')\n" +
                            "                            AND aht.DELETE_REASON_ IN ('completed','process terminated','deleted')");
            if (wfInfo != null && wfInfo.size() > 0) {
                int count = wfInfo.size();
                dbLog.info("pushDoneDel", "推送已办删除待办异常", "满足条件条数:"+count);
                for(int i=0;i<count;i++){
                    Map<String, Object> workFlow = wfInfo.get(i);

                    JSONObject jo = new JSONObject();
                    JSONArray pushJA = new JSONArray();
                    String taskid = StringHelper.nullToEmpty(workFlow.get("taskid"));
                    String userid = StringHelper.nullToEmpty(workFlow.get("userid"));
                    if (StringUtils.isEmpty(userid)) continue;
                    String compurl = StringHelper.nullToEmpty(workFlow.get("compurl"));
                    String bizurl = StringHelper.nullToEmpty(workFlow.get("bizurl"));
                    String instcode = StringHelper.nullToEmpty(workFlow.get("instcode"));
                    String billid = StringHelper.nullToEmpty(workFlow.get("billid"));
                    if (StringUtils.isEmpty(billid)) continue;
                    String funUrl = "";
                    String url = StringUtils.isEmpty(compurl) ? bizurl : compurl;
                    url = url.startsWith("/")?url.substring(1) : url;
                    String templateUrl = "wfpiid="+instcode+"&wftaskid="+taskid+"&wfotype=taskhandle&id="+billid+"&otype=view";
                    if (url.contains("?"))
                    {
                        funUrl = url + "&";
                    }
                    else
                    {
                        funUrl = url + "?";
                    }
                    funUrl = funUrl + templateUrl;
                    jo.put("taskid", taskid);
                    jo.put("title", StringHelper.nullToEmpty(workFlow.get("title")));
                    jo.put("url", funUrl);
                    jo.put("dbName", i8DbName);
                    jo.put("currentUser", userid);
                    JSONArray users = new JSONArray();
                    users.add(userid);
                    jo.put("users", users);
                    String i8taskid = StringHelper.nullToEmpty(workFlow.get("i8taskid"));
                    String i8userid = StringHelper.nullToEmpty(workFlow.get("i8userid"));
                    String i8status = StringHelper.nullToEmpty(workFlow.get("i8status"));
                    String status = "delete";
                    if (i8userid==userid && "completed".equals(i8status)) {
                        status = "done";
                    }

                    jo.put("status", status);
                    pushJA.add(jo);

                    Send(pushJA.toString());
                }
            }
        }catch (Exception ex){
            dbLog.info("pushDoneDel", "推送已办删除待办异常", ex.getMessage());
        }
    }

    /**
     * 知会接口
     * @param jsonStr
     * @return
     */
    public I8ReturnModel Procnotif(String jsonStr) {
        I8ReturnModel rv = new I8ReturnModel();
        try{
            dbLog.info("procnotif", "产品推送", jsonStr);
            /*
            {"taskid":"","piid":"487466","title":"流程描述","url":"SUP/CustomPC/CustomPCEdit?eformCode=EFORM9000000114&wfpiid=487466&wftaskid=&wfotype=processNotify&id=395230214000001&otype=view&isFromNotification=true","dbName":"NG0001","currentUser":"system","users":["450220823000005"],"status":"addNew"}
             */
            //先将接收到的数据插入中间表 AddNew 状态的数据
            JSONObject wf = JSONObject.parseObject(jsonStr);
            String piid = wf.getString("piid");

            String url = wf.getString("url");
            String dbName = wf.getString("dbName");
            if(!i8DbName.equals(dbName)) return rv; //非当前启用账套
            String currentUser = wf.getString("currentUser");
            String status = wf.getString("status");
            JSONArray usersJA = wf.getJSONArray("users");
            int userCount = usersJA.size();
            if("addNew".equals(status)) {
                //只记录AddNew数据
                for(int m=0;m<userCount;m++){
                    String userid = usersJA.getString(m);
                    String phid = GetNewPhidUtils.getPhid();
                    secDevProcnotifMsgMapper.delete(
                            new QueryWrapper<SecDevProcnotifMsg>()
                                    .lambda().
                                    eq(SecDevProcnotifMsg::getTaskid,piid)
                                    .eq(SecDevProcnotifMsg::getUserid,userid)
                                    .eq(SecDevProcnotifMsg::getPushadd,'0')
                                    .eq(SecDevProcnotifMsg::getPushdone,'0')
                                    .eq(SecDevProcnotifMsg::getPushdel,'0'));
                    //记录数据库
                    SecDevProcnotifMsg secDevTaskMsg = SecDevProcnotifMsg.builder()
                            .phid(phid).taskid(piid).userid(userid).url(url).dbname(dbName).status("addNew")
                            .build();
                    secDevProcnotifMsgMapper.insert(secDevTaskMsg);
                }
            }

            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if("addNew".equals(status))
            {
                //新增待办
                List<Map<String, Object>> wfInfo = jdbcTemplate.queryForList(
                        "SELECT p.id_ insid,p.business_key_ as title,p.START_TIME_ createdatetime,\n" +
                                "u1.phid as creatorphid,u1.userno startuserno\n" +
                                "FROM ACT_HI_PROCINST p \n" +
                                "JOIN fg3_user u1 ON u1.phid =p.START_USER_ID_\n" +
                                "where p.id_=?",piid);
                if (wfInfo != null && wfInfo.size() > 0) {
                    Map<String, Object> workFlow = wfInfo.get(0);
                    String insid = StringHelper.nullToEmpty(workFlow.get("insid"));//流程id
                    String creatorphid = StringHelper.nullToEmpty(workFlow.get("creatorphid"));//创建人phid
                    String createdatetime = bartDateFormat.format(wfInfo.get(0).get("createdatetime"));
                    String title = StringHelper.nullToEmpty(workFlow.get("title"));
                    for(int m=0;m<userCount;m++){
                        String userid = usersJA.getString(m);//接收人phid
                        JSONObject root_push = new JSONObject();
                        Fg3User receiverInfo = fg3UserMapper.selectById(userid);
                        Fg3User creatorInfo = fg3UserMapper.selectById(creatorphid);
                        String receiver = receiverInfo.getUserno();
                        String creator = creatorInfo.getUserno();

                        root_push.put("registerCode",registerCode);//注册系统编码
                        root_push.put("taskId","ZH_"+piid+"_"+userid);//第三方系统待办主键
                        root_push.put("title",title);//待办标题
                        root_push.put("senderName",creatorInfo.getUsername());//待办发起人姓名
                        //20230612增加紧急程度判断
                        if(title.endsWith("紧急")&&title.contains("中标信息风险测试")){
                            root_push.put("classify","3");
                        }else if(title.endsWith("高")&&title.contains("中标信息风险测试")){
                            root_push.put("classify","2");
                        }else{
                            root_push.put("classify","1");
                        }
                        root_push.put("contentType","知会");//内容类型
                        root_push.put("state","0");//状态0待办，1已办
                        root_push.put("thirdSenderId",creator);//第三方系统发送者主键
                        root_push.put("thirdReceiverId",receiver);//第三方系统接收人主键
                        root_push.put("creationDate",createdatetime);//待办发起日期，格式yyyy-MM-dd HH:mm:ss
                        root_push.put("content","");//原生app的下载地址

                        root_push.put("noneBindingSender",creator);//登录名称/人员编码/手机号/电子邮件
                        root_push.put("noneBindingReceiver",receiver);//登录名称/人员编码/手机号/电子邮件

                        //组装PCurl链接地址
                        String pwd = StringHelper.nullToEmpty(receiverInfo.getPwd());
                        String org = receiverInfo.getLastloginorg();
                        if (url.startsWith("/")) {
                            url = url.substring(1);
                        }//统一去掉第一个斜杠
                        String base64openUrl = URLEncoder.encode(url, "UTF-8");
                        //Sup/NG3WebLogin/SignLogin
                        String pcurl = i8Url + "/Hnlj/TaskMsg/wfmsg?logid=" + receiver+ "&pwd=" + URLEncoder.encode(pwd, "UTF-8") + "&database=" + i8DbName + "&orgid=" + org + "&openUrl=" + base64openUrl + "&urlTitle=" + URLEncoder.encode(title, "UTF-8") + "&openAlone=true";

                        root_push.put("url",pcurl);//PC穿透地址
                        //组装app链接地址
                        JSONObject pushdata = new JSONObject();
                        JSONObject pushdatadata = new JSONObject();
                        pushdatadata.put("piid", insid);
                        pushdatadata.put("taskinstid", "");
                        pushdatadata.put("isNotification", true);
                        pushdata.put("data", pushdatadata);
                        String pushdd = URLEncoder.encode(pushdata.toJSONString(), "UTF-8");
                        String appurl = i8App + "&requestType=MEA&defaultTab=1&userid=" + receiver + "_" + i8DbName.replace("NG","") + "&pushdata=" + pushdd;
                        root_push.put("h5url",appurl);//H5穿透地址

                        StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                        entity.setContentType("application/json");
                        Header[] headers = new Header[1];
                        Header header = new BasicHeader("Content-Type","application/json");
                        headers[0] = header;
                        //获取token
                        String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                        JSONObject tokenPush = new JSONObject();
                        tokenPush.put("userName", oaUsername);
                        tokenPush.put("password", oaPassword);
                        StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                        tokenEntity.setContentType("application/json");
                        ///"+oaUsername+"/"+oaPassword
                        String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                        String token = "";
                        if(!StringUtils.isEmpty(tokenMsg)){
                            dbLog.info("procnotif", "推送新增待办获取token", "接口返回:"+tokenMsg);
                            JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                            token = tokenJO.getString("id");
                        }
                        String addNewUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/receive?token="+token;
                        String rtnMsg = httpHelper.Post(addNewUrl,entity,headers);
                        dbLog.info("procnotif", "推送新增待办", addNewUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                        int j=0;//{"return":{"returnState":2,"message":"消息入队成功 | 4bd2a885-6af5-4c7c-91f7-89645046c17b"}}
                        //更新新增待办推送标识和时间
                        if(!StringUtils.isEmpty(rtnMsg)){
                            JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                            if("true".equals(joRtn.getString("success"))){
                                Date nowTime = new Date();
                                UpdateWrapper updateWrapper = new UpdateWrapper();
                                updateWrapper.eq("taskid", piid);
                                updateWrapper.eq("userid", userid);
                                updateWrapper.set("pushadd","1");
                                updateWrapper.set("pushaddtime",bartDateFormat.format(nowTime));
                                secDevProcnotifMsgMapper.update(null,updateWrapper);


                                //再发个消息通知
                                    /*
                                    JSONObject msgPushJO = new JSONObject();
                                    msgPushJO.put("thirdpartyRegisterCode",registerCode);//注册系统编码
                                    msgPushJO.put("thirdpartyMessageId",piId+"_"+userid);//第三方系统待办主键
                                    msgPushJO.put("messageContent",title);//待办标题
                                    msgPushJO.put("downloadUrl","");//原生app的下载地址
                                    msgPushJO.put("thirdpartySenderId",creator);//第三方系统发送者主键
                                    msgPushJO.put("thirdpartyReceiverId",receiver);//第三方系统接收人主键
                                    msgPushJO.put("creation_date",createdatetime);//待办发起日期，格式yyyy-MM-dd HH:mm:ss
                                    msgPushJO.put("noneBindingSender",creator);//登录名称/人员编码/手机号/电子邮件
                                    msgPushJO.put("noneBindingReceiver",receiver);//登录名称/人员编码/手机号/电子邮件
                                    msgPushJO.put("messageURL",pcurl);//PC穿透地址
                                    msgPushJO.put("messageH5URL",appurl);//H5穿透地址
                                    StringEntity msgEntity = new StringEntity(msgPushJO.toJSONString(), Charset.forName("UTF-8"));
                                    msgEntity.setContentType("application/json");
                                    String addMsgUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyMessage/receive/singleMessage?token="+token;
                                    String pushMsgRtn = httpHelper.Post(addMsgUrl,msgEntity,headers);
                                    dbLog.info("addMsg", "推送新增消息通知", addMsgUrl+"推送:"+msgPushJO.toJSONString()+"接口返回:"+pushMsgRtn);

                                     */
                            }
                        }


                    }
                }
            }else if("done".equals(status))
            {
                //已办
                for(int m=0;m<userCount;m++){
                    String userid = usersJA.getString(m);//接收人phid
                    JSONObject root_push = new JSONObject();
                    root_push.put("registerCode",registerCode);//注册系统编码
                    root_push.put("taskId","ZH_"+piid+"_"+userid);//第三方系统待办主键
                    root_push.put("state","1");//状态：0:未办理；1:已办理
                    root_push.put("subState","0");//处理后状态：0/1/2/3同意已办/不同意已办/取消/驳回

                    Fg3User receiverInfo = fg3UserMapper.selectById(userid);
                    String receiver = receiverInfo.getUserno();

                    StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                    entity.setContentType("application/json");
                    Header[] headers = new Header[1];
                    Header header = new BasicHeader("Content-Type","application/json");
                    headers[0] = header;
                    //获取token
                    String token = "";
                    String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                    JSONObject tokenPush = new JSONObject();
                    tokenPush.put("userName", oaUsername);
                    tokenPush.put("password", oaPassword);
                    StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                    tokenEntity.setContentType("application/json");
                    ///"+oaUsername+"/"+oaPassword
                    String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                    if(!StringUtils.isEmpty(tokenMsg)){
                        dbLog.info("procnotif", "推送已办获取token", "接口返回:"+tokenMsg);
                        JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                        token = tokenJO.getString("id");
                    }
                    String doneUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/updatePendingState?token="+token;
                    String rtnMsg = httpHelper.Post(doneUrl,entity,headers);
                    int j=0;
                    dbLog.info("procnotif", "推送已办", doneUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                    //更新新增待办推送标识和时间
                    if(!StringUtils.isEmpty(rtnMsg)){
                        JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                        if("true".equals(joRtn.getString("success"))){
                            Date nowTime = new Date();
                            UpdateWrapper updateWrapper = new UpdateWrapper();
                            updateWrapper.eq("taskid", piid);
                            updateWrapper.eq("userid", userid);
                            updateWrapper.set("pushdone","1");
                            updateWrapper.set("pushdonetime",bartDateFormat.format(nowTime));
                            secDevProcnotifMsgMapper.update(null,updateWrapper);
                        }
                    }



                }
            }else if("delete".equals(status))
            {
                //知会接口不存在删除的动作
                //删除待办
                for(int m=0;m<userCount;m++){
                    String userid = usersJA.getString(m);//接收人phid
                    JSONObject root_push = new JSONObject();
                    root_push.put("registerCode",registerCode);//注册系统编码
                    root_push.put("taskId","ZH_"+piid+"_"+userid);//第三方系统待办主键
                    root_push.put("state","1");//状态：0:未办理；1:已办理
                    root_push.put("subState","2");//处理后状态：0/1/2/3同意已办/不同意已办/取消/驳回

                    Fg3User receiverInfo = fg3UserMapper.selectById(userid);
                    String receiver = receiverInfo.getUserno();

                    StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                    entity.setContentType("application/json");
                    Header[] headers = new Header[1];
                    Header header = new BasicHeader("Content-Type","application/json");
                    headers[0] = header;
                    //获取token
                    String token = "";
                    String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                    JSONObject tokenPush = new JSONObject();
                    tokenPush.put("userName", oaUsername);
                    tokenPush.put("password", oaPassword);
                    StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                    tokenEntity.setContentType("application/json");
                    ///"+oaUsername+"/"+oaPassword
                    String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                    if(!StringUtils.isEmpty(tokenMsg)){
                        dbLog.info("procnotif", "推送删除待办获取token", "接口返回:"+tokenMsg);
                        JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                        token = tokenJO.getString("id");
                    }
                    String delUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/updatePendingState?token="+token;
                    String rtnMsg = httpHelper.Post(delUrl,entity,headers);

                    int j=0;
                    dbLog.info("procnotif", "推送删除待办", delUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                    //更新新增待办推送标识和时间
                    if(!StringUtils.isEmpty(rtnMsg)){
                        JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                        if("true".equals(joRtn.getString("success"))){
                            Date nowTime = new Date();
                            UpdateWrapper updateWrapper = new UpdateWrapper();
                            updateWrapper.eq("taskid", piid);
                            updateWrapper.eq("userid", userid);
                            updateWrapper.set("pushdel","1");
                            updateWrapper.set("pushdeltime",bartDateFormat.format(nowTime));
                            secDevProcnotifMsgMapper.update(null,updateWrapper);
                        }
                    }


                }
            }

        }catch (Exception ex){
            rv.setMessage("接口出现异常:"+ex.getMessage());
        }
        return rv;
    }

    /**
     * 催办产生的消息自由呼推送致远消息提醒
     * @param id
     * @param jsonStr
     * @return
     */
    public I8ReturnModel MessageAdd(String id, String jsonStr) {
        I8ReturnModel rv = new I8ReturnModel();
        try{
            dbLog.info("messageAdd", "产品推送", "id:"+id+";jsonStr:"+jsonStr);
            //新增待办
            List<Map<String, Object>> wfInfo = jdbcTemplate.queryForList(
                    "select fm.phid,fm.cname,fu2.phid as creatorphid,fm.sender,fm.remarks as title,fu.phid as recieverphid,msg.msgreciever," +
                            "fu.pwd,to_char(fm.sendtime,'yyyy-MM-dd HH24:mi:ss') as createtime from fg_msginfo fm\n" +
                            "left join fg_msgreciever msg on fm.phid=msg.cno\n" +
                            "left join fg3_user fu on fu.userno=msg.msgreciever\n" +
                            "left join fg3_user fu2 on fu2.userno=fm.sender\n" +
                            "where fm.phid=?",id);
            if (wfInfo != null && wfInfo.size() > 0) {
                int msgCount = wfInfo.size();
                for(int m=0;m<msgCount;m++){
                    Map<String, Object> workFlow = wfInfo.get(m);
                    String userid = StringHelper.nullToEmpty(workFlow.get("recieverphid"));//接收人phid
                    String creatorphid = StringHelper.nullToEmpty(workFlow.get("creatorphid"));//创建人phid
                    String createtime = StringHelper.nullToEmpty(workFlow.get("createtime"));
                    JSONObject root_push = new JSONObject();
                    Fg3User receiverInfo = fg3UserMapper.selectById(userid);
                    Fg3User creatorInfo = fg3UserMapper.selectById(creatorphid);
                    String receiver = receiverInfo.getUserno();
                    String creator = creatorInfo.getUserno();
                    String title = StringHelper.nullToEmpty(workFlow.get("title"));
                    String workflowname = StringHelper.nullToEmpty(workFlow.get("cname"));//流程类型名称
                    String nodename = StringHelper.nullToEmpty(workFlow.get("cname"));//步骤名称(节点名称)
                    root_push.put("registerCode",registerCode);//注册系统编码
                    root_push.put("taskId",id+"_"+userid);//第三方系统待办主键
                    root_push.put("title",title);//待办标题
                    root_push.put("senderName",creatorInfo.getUsername());//待办发起人姓名
                    root_push.put("classify",nodename);//类别
                    root_push.put("contentType",workflowname);//内容类型
                    root_push.put("state","0");//状态0待办，1已办
                    root_push.put("thirdSenderId",creator);//第三方系统发送者主键
                    root_push.put("thirdReceiverId",receiver);//第三方系统接收人主键
                    root_push.put("creationDate",createtime);//待办发起日期，格式yyyy-MM-dd HH:mm:ss
                    root_push.put("content","");//原生app的下载地址

                    root_push.put("noneBindingSender",creator);//登录名称/人员编码/手机号/电子邮件
                    root_push.put("noneBindingReceiver",receiver);//登录名称/人员编码/手机号/电子邮件

                    //组装PCurl链接地址
                    String pwd = StringHelper.nullToEmpty(receiverInfo.getPwd());
                    String org = receiverInfo.getLastloginorg();
                    String url = "WM/Common/Msg/NetCallReply?MsgCode=" + id + "&AppTitle=%E6%B6%88%E6%81%AF%E8%87%AA%E7%94%B1%E5%91%BC%E6%9F%A5%E7%9C%8B";
                    if (url.startsWith("/")) {
                        url = url.substring(1);
                    }//统一去掉第一个斜杠
                    String base64openUrl = URLEncoder.encode(url, "UTF-8");
                    //Sup/NG3WebLogin/SignLogin
                    String pcurl = i8Url + "/Hnlj/TaskMsg/wfmsg?logid=" + receiver+ "&pwd=" + URLEncoder.encode(pwd, "UTF-8") + "&database=" + i8DbName + "&orgid=" + org + "&openUrl=" + base64openUrl + "&urlTitle=" + URLEncoder.encode(title, "UTF-8") + "&openAlone=true";

                    root_push.put("url",pcurl);//PC穿透地址

                    //组装app链接地址
                    JSONObject pushdata = new JSONObject();
                    pushdata.put("module", "MMP");
                    JSONObject pushdatadata = new JSONObject();
                    pushdatadata.put("ccode", id);
                    pushdatadata.put("ncIndex", "0");
                    pushdatadata.put("hasread", "false");
                    pushdata.put("data", pushdatadata);
                    String pushdd = URLEncoder.encode(pushdata.toJSONString(), "UTF-8");
                    String appurl = i8App + "&requestType=MMP&defaultTab=1&userid=" + receiver + "_" + i8DbName.replace("NG","") + "&pushdata=" + pushdd;
                    root_push.put("h5url",appurl);//H5穿透地址

                    StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                    entity.setContentType("application/json");
                    Header[] headers = new Header[1];
                    Header header = new BasicHeader("Content-Type","application/json");
                    headers[0] = header;
                    //获取token
                    String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                    JSONObject tokenPush = new JSONObject();
                    tokenPush.put("userName", oaUsername);
                    tokenPush.put("password", oaPassword);
                    StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                    tokenEntity.setContentType("application/json");
                    ///"+oaUsername+"/"+oaPassword
                    String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                    String token = "";
                    if(!StringUtils.isEmpty(tokenMsg)){
                        dbLog.info("messageAdd", "推送新增待办获取token", "接口返回:"+tokenMsg);
                        JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                        token = tokenJO.getString("id");
                    }
                    String addNewUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/receive?token="+token;
                    //String rtnMsg = httpHelper.Post(addNewUrl,entity,headers);
                    //催办信息不发待办 直接发消息通知

                    JSONObject msgPushJO = new JSONObject();
                    msgPushJO.put("thirdpartyRegisterCode",registerCode);//注册系统编码
                    msgPushJO.put("thirdpartyMessageId",id+"_"+userid);//第三方系统待办主键
                    msgPushJO.put("messageContent",title);//待办标题
                    msgPushJO.put("downloadUrl","");//原生app的下载地址
                    msgPushJO.put("thirdpartySenderId",creator);//第三方系统发送者主键
                    msgPushJO.put("thirdpartyReceiverId",receiver);//第三方系统接收人主键
                    msgPushJO.put("creation_date",createtime);//待办发起日期，格式yyyy-MM-dd HH:mm:ss
                    msgPushJO.put("noneBindingSender",creator);//登录名称/人员编码/手机号/电子邮件
                    msgPushJO.put("noneBindingReceiver",receiver);//登录名称/人员编码/手机号/电子邮件
                    msgPushJO.put("messageURL",pcurl);//PC穿透地址
                    msgPushJO.put("messageH5URL",appurl);//H5穿透地址
                    StringEntity msgEntity = new StringEntity(msgPushJO.toJSONString(), Charset.forName("UTF-8"));
                    msgEntity.setContentType("application/json");
                    String addMsgUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyMessage/receive/singleMessage?token="+token;
                    String rtnMsg = httpHelper.Post(addMsgUrl,msgEntity,headers);
                    dbLog.info("messageAdd", "推送新增消息通知", addMsgUrl+"推送:"+msgPushJO.toJSONString()+"接口返回:"+rtnMsg);


                    //dbLog.info("messageAdd", "推送新增待办", addNewUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                    int j=0;//{"return":{"returnState":2,"message":"消息入队成功 | 4bd2a885-6af5-4c7c-91f7-89645046c17b"}}
                    //更新新增待办推送标识和时间
                    if(!StringUtils.isEmpty(rtnMsg)){
                        JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                        if("true".equals(joRtn.getString("success"))){
                            Date nowTime = new Date();
                            String phid = GetNewPhidUtils.getPhid();
                            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String addTime = bartDateFormat.format(nowTime);
                            SecDevMessage secDevMessage = SecDevMessage.builder()
                                    .phid(phid).taskid(id).userid(userid).url(url).dbname(i8DbName).status("addNew")
                                    .requestname(title).workflowname(workflowname).nodename(nodename).pushadd("1").pushaddtime(addTime)
                                    .build();
                            secDevMessageMapper.insert(secDevMessage);
                        }
                    }


                }
            }
        }catch (Exception ex){
            rv.setMessage("接口出现异常:"+ex.getMessage());
        }
        return rv;
    }

    /**
     * 接口保留  不推送致远
     * @param phids
     * @param jsonStr
     * @return
     */
    public I8ReturnModel MessageUpdate(String phids, String jsonStr) {
        I8ReturnModel rv = new I8ReturnModel();
        try{
            //催办信息不发待办 直接发消息通知
            return rv;
            /*
            dbLog.info("messageUpdate", "产品推送", "receiver:"+phids+";jsonStr:"+jsonStr);
            String paramSql = URLDecoder.decode(phids, "UTF-8");
            // (phid IN ('348210622000071','348210622000060','348210622000036','348210622000025','348210622000014','348210622000001','348210621000012'))
            // phid='348210723000001'
            paramSql = com.newgrand.utils.StringUtils.trimFirstAndLastChar(paramSql,"(");
            paramSql = com.newgrand.utils.StringUtils.trimFirstAndLastChar(paramSql,")");
            //新增待办
            List<Map<String, Object>> wfInfo = jdbcTemplate.queryForList(
                    "select fm.msgreciever as userno,fu.phid as recieverphid,msg.cname as title,msg.phid as taskid from fg_msgreciever fm\n" +
                            "left join fg_msginfo msg on fm.cno=msg.phid\n" +
                            "left join fg3_user fu on fu.userno=msg.msgreciever\n" +
                            "where fm.?",paramSql);
            if (wfInfo != null && wfInfo.size() > 0) {
                int msgCount = wfInfo.size();
                for(int m=0;m<msgCount;m++){
                    Map<String, Object> workFlow = wfInfo.get(m);
                    String userid = StringHelper.nullToEmpty(workFlow.get("recieverphid"));//接收人phid
                    String taskid = StringHelper.nullToEmpty(workFlow.get("taskid"));
                    JSONObject root_push = new JSONObject();
                    root_push.put("registerCode",registerCode);//注册系统编码
                    root_push.put("taskId",taskid+"_"+userid);//第三方系统待办主键
                    root_push.put("state","1");//状态：0:未办理；1:已办理
                    root_push.put("subState","0");//处理后状态：0/1/2/3同意已办/不同意已办/取消/驳回

                    StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                    entity.setContentType("application/json");
                    Header[] headers = new Header[1];
                    Header header = new BasicHeader("Content-Type","application/json");
                    headers[0] = header;
                    //获取token
                    String token = "";
                    String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                    JSONObject tokenPush = new JSONObject();
                    tokenPush.put("userName", oaUsername);
                    tokenPush.put("password", oaPassword);
                    StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                    tokenEntity.setContentType("application/json");
                    ///"+oaUsername+"/"+oaPassword
                    String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                    if(!StringUtils.isEmpty(tokenMsg)){
                        dbLog.info("messageUpdate", "推送已办获取token", "接口返回:"+tokenMsg);
                        JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                        token = tokenJO.getString("id");
                    }
                    String doneUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/updatePendingState?token="+token;
                    String rtnMsg = httpHelper.Post(doneUrl,entity,headers);
                    int j=0;
                    dbLog.info("messageUpdate", "推送已办", doneUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                    //更新新增待办推送标识和时间
                    if(!StringUtils.isEmpty(rtnMsg)){
                        JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                        if("true".equals(joRtn.getString("success"))){
                            Date nowTime = new Date();
                            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            UpdateWrapper updateWrapper = new UpdateWrapper();
                            updateWrapper.eq("taskid", taskid);
                            updateWrapper.eq("userid", userid);
                            updateWrapper.set("pushdone","1");
                            updateWrapper.set("pushdonetime",bartDateFormat.format(nowTime));
                            secDevMessageMapper.update(null,updateWrapper);
                        }
                    }



                }
            }

             */
        }catch (Exception ex){
            rv.setMessage("接口出现异常:"+ex.getMessage());
        }
        return rv;
    }

    /**
     * 接口保留  不推送致远
     * @param phids
     * @param jsonStr
     * @return
     */
    public I8ReturnModel MessageDelete(String phids, String jsonStr) {
        I8ReturnModel rv = new I8ReturnModel();
        try{
            //催办信息不发待办 直接发消息通知
            return rv;
            /*
            dbLog.info("messageDelete", "产品推送", "receiver:"+phids+";jsonStr:"+jsonStr);
            String paramSql = URLDecoder.decode(phids, "UTF-8");
            paramSql = " in ('"+ com.newgrand.utils.StringUtils.trimFirstAndLastChar(paramSql,"'")+"')";
            //receiver  348210618000073
            //receiver '348210618000062','348210618000051'
            //新增待办
            List<Map<String, Object>> wfInfo = jdbcTemplate.queryForList(
                    "select fm.msgreciever as userno,fu.phid as recieverphid,msg.phid as taskid from fg_msgreciever fm\n" +
                            "left join fg_msginfo msg on fm.cno=msg.phid\n" +
                            "left join fg3_user fu on fu.userno=msg.msgreciever\n" +
                            "where fm.phid ?",paramSql);
            if (wfInfo != null && wfInfo.size() > 0) {
                int msgCount = wfInfo.size();
                for(int m=0;m<msgCount;m++){
                    Map<String, Object> workFlow = wfInfo.get(m);
                    String userid = StringHelper.nullToEmpty(workFlow.get("recieverphid"));//接收人phid
                    String taskid = StringHelper.nullToEmpty(workFlow.get("taskid"));
                    JSONObject root_push = new JSONObject();
                    root_push.put("registerCode",registerCode);//注册系统编码
                    root_push.put("taskId",taskid+"_"+userid);//第三方系统待办主键
                    root_push.put("state","1");//状态：0:未办理；1:已办理
                    root_push.put("subState","2");//处理后状态：0/1/2/3同意已办/不同意已办/取消/驳回


                    StringEntity entity = new StringEntity(root_push.toJSONString(), Charset.forName("UTF-8"));
                    entity.setContentType("application/json");
                    Header[] headers = new Header[1];
                    Header header = new BasicHeader("Content-Type","application/json");
                    headers[0] = header;
                    //获取token
                    String token = "";
                    String tokenUrl = env.Get("oa.url")+"/seeyon/rest/token";
                    JSONObject tokenPush = new JSONObject();
                    tokenPush.put("userName", oaUsername);
                    tokenPush.put("password", oaPassword);
                    StringEntity tokenEntity = new StringEntity(tokenPush.toJSONString(), Charset.forName("UTF-8"));
                    tokenEntity.setContentType("application/json");
                    ///"+oaUsername+"/"+oaPassword
                    String tokenMsg = httpHelper.Post(tokenUrl,tokenEntity,headers);
                    if(!StringUtils.isEmpty(tokenMsg)){
                        dbLog.info("messageDelete", "推送删除待办获取token", "接口返回:"+tokenMsg);
                        JSONObject tokenJO = JSONObject.parseObject(tokenMsg);
                        token = tokenJO.getString("id");
                    }
                    String delUrl = env.Get("oa.url")+"/seeyon/rest/thirdpartyPending/updatePendingState?token="+token;
                    String rtnMsg = httpHelper.Post(delUrl,entity,headers);

                    int j=0;
                    dbLog.info("messageDelete", "推送删除待办", delUrl+"推送:"+root_push.toJSONString()+"接口返回:"+rtnMsg);
                    //更新新增待办推送标识和时间
                    if(!StringUtils.isEmpty(rtnMsg)){
                        JSONObject joRtn = JSONObject.parseObject(rtnMsg);
                        if("true".equals(joRtn.getString("success"))){
                            Date nowTime = new Date();
                            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            UpdateWrapper updateWrapper = new UpdateWrapper();
                            updateWrapper.eq("taskid", taskid);
                            updateWrapper.eq("userid", userid);
                            updateWrapper.set("pushdel","1");
                            updateWrapper.set("pushdeltime",bartDateFormat.format(nowTime));
                            secDevTaskMsgMapper.update(null,updateWrapper);
                        }
                    }


                }
            }

             */
        }catch (Exception ex){
            rv.setMessage("接口出现异常:"+ex.getMessage());
        }
        return rv;
    }
}
